package com.wnhz.work.jy.fragment;


import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wnhz.work.jy.R;
import com.wnhz.work.jy.activity.GoodDetailsMainActivity;
import com.wnhz.work.jy.adapter.PicViewPagerAdapter;
import com.wnhz.work.jy.utils.AddImages;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * ----图文详情
 */
public class PicTextDetailsFragment extends Fragment implements View.OnClickListener {
    private static final int PICTEXTDETAILS = 87;
    private View view;
    private TextView tv_oldTitle;

    private TextView tv_title;
    private TextView tv_sell_num;
    private TextView tv_money;
    private TextView tv_free_text1;

    //String url = "https://www.baidu.com/";
    GoodDetailsMainActivity activity;
    private ViewPager viewPager;
    private LinearLayout indicatorLayout;
    private int currentPosition;
    private ImageView[] indicators;
    private ArrayList<View> viewList = new ArrayList<>();// 添加了首尾的轮播图集合
    private List<String> autoPlayImages = new ArrayList<>();// 轮播图的图片资源集合
    private TextView tv_delivery;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case PICTEXTDETAILS:
                    int position = currentPosition + 1;
                    viewPager.setCurrentItem(position, true);
                    break;
            }
        }
    };
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (GoodDetailsMainActivity) getActivity();
        view = inflater.inflate(R.layout.fragment_pic_text_details, container, false);
        initView();
        return view;
    }

    public void setData(){
        if (activity.goodDetailsBean != null){
            tv_title.setText(activity.goodDetailsBean.getGoodName());
            tv_money.setText("¥"+activity.goodDetailsBean.getGoodPrice());
            tv_free_text1.setText("购买此商品，每一枚都可获得"+activity.goodDetailsBean.getReceiveRewards()+"积分。");
            tv_sell_num.setText("月销量："+activity.goodDetailsBean.getSales());
            tv_delivery.setText("库存: "+activity.goodDetailsBean.getStoreNum()+"件");
            autoPlayImages.clear();
            if (activity.goodDetailsBean.getGoodImgArr() != null && activity.goodDetailsBean.getGoodImgArr().size()>0){
                autoPlayImages.addAll(activity.goodDetailsBean.getGoodImgArr());
            }else {
                autoPlayImages.add(activity.goodDetailsBean.getGoodImg());
            }

            initViewPager();
            setViewPager();
        }

    }

    private void initView() {
        viewPager = (ViewPager) view.findViewById(R.id.homepager_viewpager);
        indicatorLayout = (LinearLayout) view.findViewById(R.id.homepager_indicator);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_money = (TextView) view.findViewById(R.id.tv_money);
        tv_sell_num = (TextView) view.findViewById(R.id.tv_sell_num);
        tv_free_text1 = (TextView) view.findViewById(R.id.tv_free_text1);
        tv_delivery = (TextView) view.findViewById(R.id.tv_delivery);
//        tv_oldTitle = (TextView) view.findViewById(R.id.tv_oldTitle);
//
//        tv_oldTitle.getPaint().setAntiAlias(true);//抗锯齿
//
//        tv_oldTitle.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG); //中划线


    }

    private int width;
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        WindowManager wm = (WindowManager) activity
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewPager.getLayoutParams();
        params.height = width;
        viewPager.setLayoutParams(params);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    public void initWeb(String url) {
        WebView webView = (WebView) view.findViewById(R.id.webview);
        // WebView加载web资源
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(false);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        activity.showDialog();
        if (url != null) {
            webView.loadUrl(url);
            //webView.loadUrl("http://dongtingyueh.blog.163.com/blog/static/4619453201351951933151/");
        }
        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    activity.closeDialog();

                } else {
                    // 加载中

                }
            }
        });


    }

    private void setViewPager() {
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                currentPosition = arg0;
                if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                    setIndicator(autoPlayImages.size() - 1);
                } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                    setIndicator(0);
                } else {

                    setIndicator(currentPosition - 1);
                }

            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
                if (arg0 == 0) {
                    handler.removeMessages(PICTEXTDETAILS);
                    Message message = new Message();
                    message.what = PICTEXTDETAILS;
                    handler.sendMessageDelayed(message, 3000);
                    viewPager.setCurrentItem(currentPosition, false);
                    if (viewList.size() > 1) { // 多于1，才会循环跳转
                        if (currentPosition < 1) { // 首位之前，跳转到末尾（N）
                            currentPosition = autoPlayImages.size(); // 注意这里是mList，而不是mViews
                            viewPager.setCurrentItem(currentPosition, false);
                        } else if (currentPosition > autoPlayImages.size()) { // 末位之后，跳转到首位（1）
                            viewPager.setCurrentItem(currentPosition, true); // false:不显示跳转过程的动画
                            viewPager.setCurrentItem(1, false); // false:不显示跳转过程的动画
                            currentPosition = 1;
                        }

                    }
                }

            }
        });

//        setIndicator(0);
        currentPosition = 1;
        viewPager.setCurrentItem(currentPosition, false);
        handler.removeMessages(PICTEXTDETAILS);
        Message message = new Message();
        message.what = PICTEXTDETAILS;
        handler.sendMessageDelayed(message, 3000);
    }

    private void initViewPager() {

        int indicatorSize = autoPlayImages.size();

        indicators = new ImageView[indicatorSize];

        for (int i = 0; i < indicators.length; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_indicator, null);
            indicators[i] = (ImageView) view.findViewById(R.id.image_indicator);
            indicatorLayout.addView(view);
        }

        viewList = AddImages.addImageDatas(getActivity(), autoPlayImages,activity.options);

        viewPager.setAdapter(new PicViewPagerAdapter(viewList, new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // System.out.println("点击了轮播图ffffff");
                // Intent intent = new Intent(getActivity(), GoodsDetail.class);
                // startActivity(intent);
            }
        }));
        if (indicators.length>1){
            viewPager.setCurrentItem(1,false);
        }
    }

    /**
     * 设置指示器
     *
     * @param selectedPosition 默认指示器位置
     */
    private void setIndicator(int selectedPosition) {


        for (int i = 0; i < indicators.length; i++) {
            indicators[i].setBackgroundResource(R.drawable.icon_point);
        }
        if (indicators.length > selectedPosition)
            indicators[selectedPosition].setBackgroundResource(R.drawable.icon_point_pre);
    }
}
